package com.myapp.ruyixing.http;

import org.json.JSONArray;
import org.json.JSONObject;

import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.JsonIOException;
import com.google.gson.JsonSyntaxException;

public class RYJSONParser {
	private static final String TAG = "RYJSONParser";

	public static final int NO_ERROR = 0;
	public static final int MISSING_ERRNO = 1000;

	public Object parse(JSONArray jsonArray) {
		return null;
	}

	public Object parse(JSONObject jsonObject) {
		return null;
	}

	protected int getErrno(JSONObject jsonObject) {
		int errno = jsonObject.optInt("errno", MISSING_ERRNO);
		if (errno == MISSING_ERRNO) {
			errno = jsonObject.optInt("error", MISSING_ERRNO);
		}
		if (errno != NO_ERROR) {
			Log.e(TAG, "errno=" + errno);
			Log.e(TAG, "msg=" + getMessage(jsonObject));
		}
		return errno;
	}

	protected String getMessage(JSONObject jsonObject) {
		return jsonObject.optString("msg");
	}

	protected <T> T loadByGson(JSONObject jsonObject, Class<T> clazz) {
		return loadByGson(jsonObject.toString(), clazz);
	}

	protected <T> T loadByGson(String json, Class<T> clazz) {
		try {
			return new Gson().fromJson(json, clazz);
		} catch (JsonSyntaxException e) {
			e.printStackTrace();
		} catch (JsonIOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}
}
